<template>
  <div id = "login">
    <div class="user-title">
      <p>用户登录</p>
    </div>
    <el-input v-model="loginForm.username" placeholder="用户名" style="width: 200px"></el-input><br>
    <el-input type="password" v-model="loginForm.password" placeholder="密码" style="width: 200px"></el-input><br><br>
    <el-button @click="login" round>登录</el-button>
  </div>
</template>

<script>
  import { mapMutations } from 'vuex';
  export default {
    data () {
      return {
        loginForm: {
          username: '',
          password: ''
        },
        userToken: ''
      };
    },

    methods: {
      ...mapMutations(['changeLogin']),
      login () {
        if (this.loginForm.username === '' || this.loginForm.password === '') {
          alert('账号或密码不能为空');
        }
        else {
          this.$axios({
            method: 'post',
            url: 'http://127.0.0.1:8004/api/login',
            data: this.loginForm
          }).then(res => {
            console.log(res)
            console.log(res.data.data)
            this.userToken = 'Bearer ' + res.data.data.token;

            // 将用户token保存到vuex中
            this.changeLogin({ Authorization: this.userToken });
            this.$router.push('/home');
            alert('登陆成功');
          }).catch(error => {
            alert('账号或密码错误');
            console.log(error);
          });
        }
      }
    }
  };

</script>
